﻿using BCGM.MedicalWisdom.IServices;
using BCGM.MedicalWisdom.Model.Models;
using BCGM.MedicalWisdom.Services.BASE;
using BCGM.MedicalWisdom.Repository.BASE;
using System.Threading.Tasks;
using System.Linq.Expressions;
using System;
using BCGM.MedicalWisdom.Model.ViewModels.Order;
using BCGM.MedicalWisdom.Model;
using SqlSugar;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using System.Linq;
using AutoMapper;
using BCGM.MedicalWisdom.Common;

namespace BCGM.MedicalWisdom.Services
{
    public class DrugOrderServices : BaseServices<DrugOrder>, IDrugOrderServices
    {
        private readonly IBaseRepository<DrugOrder> _dal;
        private readonly IBaseRepository<DrugOrderItem> _drugOrderItem;
        private readonly IConfiguration _configuration;
        private readonly IMapper _mapper;
        private readonly IRedisCacheManager _redis;
        public DrugOrderServices(IBaseRepository<DrugOrder> dal, IBaseRepository<DrugOrderItem> drugOrderItem, IConfiguration configuration, IMapper mapper,IRedisCacheManager redis)
        {
            this._dal = dal;
            base.BaseDal = dal;
            _drugOrderItem = drugOrderItem;
            _configuration = configuration;
            _mapper = mapper;
            _redis = redis;
        }
        /// <summary>
        /// 药品订单显示 dto输出 表达式树
        /// </summary>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public async Task<PageModel<DrugOrderOutputDto>> GetDrugOrder(int pageIndex = 1, int pageSize = 20, string orderByFields = null)
        {
            //关联表达式
            Expression<Func<DrugOrder, DrugOrderItem, object[]>>
                joinExpression = (DrugOrder, DrugOrderItem) => new object[] { JoinType.Left, DrugOrder.DrugOrderId == DrugOrderItem.OrderId };
            List<DrugOrder> drugOrder = await _dal.Query();
            DrugOrderOutputDto drugOrderDto = _mapper.Map<DrugOrderOutputDto>(drugOrder);
            //返回表达式
            Expression<Func<DrugOrder, DrugOrderItem, DrugOrderOutputDto>>
                selectExpression = (DrugOrder, DrugOrderItem) => drugOrderDto;
            //查询表达式
            Expression<Func<DrugOrderOutputDto, bool>> whereExpression = DrugOrder => DrugOrder.IsDeleted == false;
            var list = await base.BaseDal.QueryTabsPage
                (
                joinExpression, selectExpression, whereExpression, pageIndex, pageSize, orderByFields
                );
            return list;
        }
        /// <summary>
        /// sql语句药品订单详细两表联查显示
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<DrugOrderOutputDto>> GetDrugOrderSql()
        {
            string sql = "select * from DrugOrder where IsDeleted = 0;";
            var list = await base.BaseDal.QuerySql(sql);
            var drugOrders = _mapper.Map<List<DrugOrderOutputDto>>(list);
            return drugOrders;
        }
        /// <summary>

        /// </summary>
        /// <param name="carDto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> AddDrugRedis(DrugCarDto carDto)
        {
            //CSRedisClient cSRedis = new(_configuration.GetSection("Redis").Value);
            List<DrugCarDto> drugsCar = new();
            //查询Redis HGet是否存在已添加的数据
            drugsCar  = await _redis.HGet<List<DrugCarDto>>("DrugCar",carDto.UserId);
            
            //判断Redis存储购物车是否有数据 无 则新实例化
            drugsCar ??= new();
            //查询新增商品与购物车存在商品是否一致，如一致则进行商品数量的添加
            var oldDrug = drugsCar.Where(x => x.UserId.Equals(carDto.UserId) && x.DrugId.Equals(carDto.DrugId) && x.DrugSkuId.Equals(carDto.DrugSkuId)).FirstOrDefault();
            if (oldDrug != null)
            {
                drugsCar.Remove(oldDrug);
                carDto.DrugCarNum += oldDrug.DrugCarNum;
            }
            drugsCar.Add(carDto);
            //return cSRedis.HSet("DrugCar", carDto.UserId, drugsCar);
            return await _redis.HSet("DrugCar", carDto.UserId, drugsCar);
        }
        /// <summary>
        /// 获取药品购物车数据
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns></returns>
        public async Task<List<DrugCarDto>> GetDrugCarRedis(string userId)
        {
            //CSRedisClient cSRedis = new(_configuration.GetSection("Redis").Value);
            List<DrugCarDto> drugsCar = await _redis.HGet<List<DrugCarDto>>("DrugCar", userId);
            return drugsCar;
        }
        /// <summary>
        /// 删除用户药品购物车数据
        /// </summary>
        /// <param name="carDto"></param>
        /// <returns></returns>
        public async Task<bool> RemoveDrugCarRedis(DrugCarDto carDto)
        {
            //CSRedisClient cSRedis = new(_configuration.GetSection("Redis").Value);
            List<DrugCarDto> drugsCar = new();
            //查询Redis HGet是否存在已添加的数据
            drugsCar = await _redis.HGet<List<DrugCarDto>>("DrugCar", carDto.UserId);
            //判断Redis存储购物车是否有数据 无 则新实例化
            drugsCar ??= new();
            //查询新增商品与购物车存在商品是否一致，如一致则进行商品数量的添加
            var oldDrug = drugsCar.Where(x => x.UserId.Equals(carDto.UserId) && x.DrugId.Equals(carDto.DrugId) && x.DrugSkuId.Equals(carDto.DrugSkuId) && x.DrugCarNum == carDto.DrugCarNum).FirstOrDefault();
            if (oldDrug != null)
            {
                drugsCar.Remove(oldDrug);
            }
            return await _redis.HSet("DrugCar", carDto.UserId, drugsCar);
        }
        /// <summary>
        /// 修改用户购物车药品购买数量
        /// </summary>
        /// <param name="carDto"></param>
        /// <returns></returns>
        public async Task<bool> UptDrugCarRedis(DrugCarDto carDto)
        {
            //CSRedisClient cSRedis = new(_configuration.GetSection("Redis").Value);
            List<DrugCarDto> drugsCar = new();
            //查询Redis HGet是否存在已添加的数据
            drugsCar = await _redis.HGet<List<DrugCarDto>>("DrugCar", carDto.UserId);
            //判断Redis存储购物车是否有数据 无 则新实例化
            drugsCar ??= new();
            //查询新增商品与购物车存在商品是否一致，如一致则进行商品数量的添加
            var oldDrug = drugsCar.Where(x => x.UserId.Equals(carDto.UserId) && x.DrugId.Equals(carDto.DrugId) && x.DrugSkuId.Equals(carDto.DrugSkuId)).FirstOrDefault();
            if (oldDrug != null)
            {
                drugsCar.Remove(oldDrug);
                oldDrug.DrugCarNum = carDto.DrugCarNum;
            }
            drugsCar.Add(carDto);
            return await _redis.HSet("DrugCar", carDto.UserId, drugsCar);
        }
    }
}